/******************************************************************
 * HttpUtils.java
 * Copyright 2017 by CEIEC Company. All Rights Reserved.
 * CreateDate：2017年5月11日
 * Author：李涛
 * Version：1.0.0
 ******************************************************************/

package com.ceiec.cad.util;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * <b>修改记录：</b>
 * <p>
 * <li>
 * <p>
 * ---- 李涛 2017年5月11日
 * </li>
 * </p>
 * <p>
 * <b>类说明：</b>
 * <p>
 * HTTP工具类
 * </p>
 */
public final class HttpClientUtils {


    private static int TIMEOUT = 30000;

    private static final String APPLICATION_JSON = "application/json";

    private static final int BUFFER_SIZE = 1024;

    /**
     * 编码格式
     */
    private static final String CODE_STYLE = "UTF-8";

    public static final String UTF8 = "UTF-8";

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);



    private HttpClientUtils() {

    }

    /**
     * POST方式提交请求
     *
     * @param url  请求地址
     * @param json JSON格式请求内容
     * @throws IOException
     */
    public static String doPost(String url, String json) {
        //计时
        StopWatch timer = new StopWatch();
        timer.start();

        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
        StringEntity stringEntity = new StringEntity(json, UTF8);
        stringEntity.setContentType(APPLICATION_JSON);
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
        httpPost.setEntity(stringEntity);
        httpPost.setConfig(defaultRequestConfig);
        CloseableHttpResponse response = null;
        String responseContent = "";
        InputStream is = null;
        try {
            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            logger.debug("response status: " + status);
            if (status >= 200 && status < 300) {
                is = new BufferedInputStream(response.getEntity().getContent(), BUFFER_SIZE);
                Header header = response.getFirstHeader("Content-Length");
                int contentLength = null != header ? Integer.valueOf(header.getValue()) : 0;
                byte[] bytes = new byte[contentLength];
                int readCount = 0;
                while (readCount < contentLength) {
                    readCount += is.read(bytes, readCount, contentLength - readCount);
                }
                responseContent = new String(bytes, UTF8);
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        } catch (Exception e) {
            logger.error("error occured.{}", e);
            throw new RuntimeException(e);
        } finally {
            timer.stop();
            logger.info("doPost. requestUrl:{}, param:{},response:{},took {} ms", url, json, responseContent, timer.getTime());

            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(httpClient);
        }
        return responseContent;
    }

    /**
     * get请求
     *
     * @param url    请求地址
     * @param params 请求参数 eg: p1=v1&p2=v2
     * @return
     * @throws IOException
     */
    public static String doGet(String url, String params) throws IOException {
        logger.info("http req: {}, params: {}", url, params);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        HttpGet httpGet = new HttpGet(url + "?" + params);
        httpGet.setConfig(defaultRequestConfig);
        CloseableHttpResponse response = null;
        String responseContent = "";
        InputStream is = null;
        try {
            response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            logger.debug("response status: " + status);
            if (status >= 200 && status < 300) {
                responseContent = EntityUtils.toString(response.getEntity(), CODE_STYLE);
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        } catch (ClientProtocolException e) {
            throw new ClientProtocolException(e);
        } catch (IOException e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(httpClient);

        }
        return responseContent;
    }


}
